from PyQt4 import QtGui, QtCore

from limber.documents import basetextdocument
from limber.views import view

from limber.componentparser import ComponentInfos


class BaseTextView(view.AbstractView, QtGui.QPlainTextEdit):

    new_document_setted = QtCore.pyqtSignal((), (object,), name='newDocumentSetted')
    title_changed = QtCore.pyqtSignal((), (unicode,), name='titleChanged')

    def __init__(self, parent, document):
        super(BaseTextView, self).__init__(parent, document)
        super(view.AbstractView, self).__init__(parent)

        self._document.document_modified.connect(self._document_modified)
        self._document.title_changed[unicode].connect(self.set_title)
        self._document.document_loaded.connect(self._document_loaded)

        self._document_loaded()

    def document(self):
        '''Return the view document.'''

        return self._document

    def set_document(self, document):
        '''Sets the view document.'''

        query = basetextdocument.BaseTextDocumentQuery(from_pos=0, to_pos=-1)
        text = document.data(query)
        self.setPlainText(text)
        super(BaseTextView, self).set_document(document)

    def set_title(self, title):
        '''Sets the title of the view.'''

        old_title = self.title()
        try:
            doc_title, num = old_title.split()
            if num.strip().isdigit():
                view_number = int(num)
                new_title = '%s %d' % (title, view_number)
            else:
                new_title = title
        except ValueError:
            new_title = title

        self._title = new_title
        self.emit_title_changed(self._title)

    def _document_modified(self):
        '''Called when the document emits the *documentModified* signal.'''

        query = basetextdocument.BaseTextDocumentQuery(from_pos=0, to_pos=-1)
        self.setPlainText(self._document.data(query))

    _document_loaded = _document_modified


INFOS_DICT = {
    'name' : 'basetextview',
    'version' : '0.1.0',
    'full_name' : 'Base Text View',
    'class_name' : 'BaseTextView',
    'directory' : '../Widgets',
    'filename' : 'basetextview.py',
    'short_description' : 'A simple text view.',
    'author' : 'Giacomo Alzetta',
    'interface' : 'view',
    'abilities' : 'VIEW:TABBABLE_VIEW'
    }

COMPONENT_FILE_CONTENT = '''\
name = %(name)s
full_name = %(full_name)s
class_name = %(class_name)s
directory = %(directory)s
filename = %(filename)s
version = %(version)s
short_description = %(short_description)s
author = %(author)s
interface = %(interface)s
abilities = %(abilities)s
''' % (INFOS_DICT)

_better_infos = dict(INFOS_DICT)
_better_infos['abilities'] = INFOS_DICT['abilities'].split(':')

INFOS = ComponentInfos(**_better_infos)

del _better_infos